package com.xp.flower.qsd.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xp.flower.common.utils.CheckoutUtil;
import com.xp.flower.qsd.share.token.JsApiSignature;
import com.xp.flower.qsd.share.util.SignUtil;
import com.xp.flower.qsd.share.util.TokenHandler;
import com.xp.flower.qsd.utils.weixin.WeiXinGlobalConstants;

@Controller
@RequestMapping("weiXinController")
public class WeiXinController {
    
    @RequestMapping("/validate")
    public void validate(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print;
        if (isGet) {
            // 微信加密签名 
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 微信分享
     * 说明：
     * @param url
     * @return
     * @author 刘品呈
     * @time：2017年10月19日 上午8:29:18
     */
    @ResponseBody
    @RequestMapping(value = "/wechat/share")
    public Object loadWechatShareData(String url){
       String appId = WeiXinGlobalConstants.getProperties("appId");
       String ticket = TokenHandler.getJsApiTicket(appId, WeiXinGlobalConstants.getProperties("appSecret"));
       JsApiSignature result = SignUtil.getJSApiSignature(ticket, url);
       result.setAppId(appId);
       return result;
    }
    
    
}